package com.jk.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.jk.srb.oss.service.FileService;
import com.jk.srb.oss.utils.OssProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Classname FileServiceImpl
 * @Description TODO
 * @Date 2021/5/27 11:12
 * @Created by jk
 */
@Service
public class FileServiceImpl implements FileService {
    @Resource
    private OssProperties ossProperties;

    @Override
    public String upload(InputStream inputStream, String module, String fileName) {
        // 创建OSSClient实例。
        OSS ossClient = createOssClient();
        //判断oss实例是否存在：如果不存在则创建，如果存在则获取
        if (!ossClient.doesBucketExist(ossProperties.getBucketName())) {
            //创建bucket
            ossClient.createBucket(ossProperties.getBucketName());
            //设置oss实例的访问权限：公共读
            ossClient.setBucketAcl(ossProperties.getBucketName(), CannedAccessControlList.PublicRead);
        }
        //构建日期路径：avatar/2019/02/26/文件名
        String folder = new DateTime().toString("yyyy/MM/dd");
        //文件名：uuid.扩展名
        fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        //文件根路径
        String key = module + "/" + folder + "/" + fileName;
        //文件上传至阿里云
        ossClient.putObject(ossProperties.getBucketName(), key, inputStream);
        // 关闭OSSClient
        ossClient.shutdown();
        //阿里云文件绝对路径
        return "https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint() + "/" + key;
    }

    @Override
    public void removeFile(String url) {
        OSS ossClient = createOssClient();
        //文件名（服务器上的文件路径）
        String host = "https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint() + "/";
        String objectName = url.substring(host.length());
        ossClient.deleteObject(ossProperties.getBucketName(), objectName);
        // 关闭OSSClient
        ossClient.shutdown();
    }

    private OSS createOssClient() {
        // 创建OSSClient实例。
        return new OSSClientBuilder().build(
                ossProperties.getEndpoint(),
                ossProperties.getKeyId(),
                ossProperties.getKeySecret());
    }
}
